import { Component, ElementRef, OnInit } from '@angular/core';
import { Options, Rect, Topology } from 'topology-core';
import { FetchService } from '../../../../core/net/fetch.service';
import * as _ from 'lodash';

@Component({
  selector: 'app-gate-control-diagram',
  templateUrl: './gate-control-diagram.component.html',
  styleUrls: ['./gate-control-diagram.component.scss']
})
export class GateControlDiagramComponent implements OnInit {
    infoShow = false;
    hoverItem = {
        top: '0px',
        left: '0px',
        alertLevel: '-',
        waterLevel: '-',
        limitTraffic: '-',
        flow: '-'
    };
    glcData;
    canvas: Topology;
    rect: Rect;
    canvasOptions: Options = {};
    // gate		闸门
    // gate_out 	退水闸
    // pump		泵站
    // ZZ			水位站
    // ZQ			水文站
    // text_h		水位
    // text_q		流量
  constructor(private fetchService: FetchService,
              private el: ElementRef,) { }

  ngOnInit(): void {
      window.addEventListener('resize', this.debounce(() => {
          this.onResize();
      }, 500));
      this.getMapData2();
  }
    // 窗口变化
    onResize() {
        console.log('windonw is resize');
        const h = this.el.nativeElement.querySelector('.canvas-wrap').getBoundingClientRect().height;
        const w = this.el.nativeElement.querySelector('.canvas-wrap').getBoundingClientRect().width; // 设置画布
        this.rect = this.canvas.getRect();
        if (this.rect.width / this.rect.height > w / h) {
            this.canvas.scale(w / this.rect.width * 0.9);
        } else {
            this.canvas.scale(h / this.rect.height);
        }
        this.canvas.translate(w / 2 - this.rect.center.x, h / 2 - this.rect.center.y);
    }
    getMapData2(): void {
        this.fetchService.post<any>('schedule/actualDispatchMonData/data', {manageId: '1'}).subscribe(r => {
            this.glcData = r;
            this.fetchService.get<any>('assets/data/glcnew/1.json').subscribe(res => {
                const pens = res.pens;
                // 数据处理
                this.glcData.map(feature => {
                    for (const pen of pens) {
                        // 修改闸门颜色
                        if (pen.data.cid == feature.objId) {
                            pen.image = '/yjq_web/assets/images/ght/newicons/' + feature.objType + feature.status + '.png';
                        }
                        // 修改q
                        if (pen.data.cid == `${feature.objId}q`) {
                            pen.text = feature.flow ? feature.flow + 'm³/s' : '-m³/s';
                        }
                        // 修改h
                        if (pen.data.cid == `${feature.objId}h`) {
                            pen.text = feature.waterLevel ? feature.waterLevel + 'm' : '-m';
                        }
                    }
                });

                if (this.canvas) {
                    // 重置画布数据
                    this.canvas.open({
                        id: '',
                        version: '',
                        name: 'new空白文件',
                        desc: '',
                        image: '',
                        userId: '',
                        class: '',
                        component: false,
                        shared: false
                    });
                } else {
                    // 创建画布
                    this.canvasOptions.on = this.onMouseEvent;
                    this.canvas = new Topology('topology-canvas', this.canvasOptions);
                }
                this.canvas.open(res);

                // 设置画布
                this.onResize();
            });
        });
    }
    // 概化图元素事件
    onMouseEvent = (event: string, node: any) => {
        if (event === 'moveInNode') {
            if (node.data != '' && (['ZZ', 'ZQ', 'gate', 'gate_out'].indexOf(node.data.type) > -1)) {
                console.log(event, node);
                this.infoShow = true;
                const yArr = [node.rotatedAnchors[0].y, node.rotatedAnchors[1].y, node.rotatedAnchors[2].y, node.rotatedAnchors[3].y];
                const featureH = _.max(yArr) - _.min(yArr);
                console.log(featureH);
                this.hoverItem.top = (node.rect.center.y - 120 - featureH / 2 + 10) + 'px';
                this.hoverItem.left = (node.rect.center.x - 76) + 'px';
                const nodeId = node.data.cid;
                this.glcData.map(item => {
                    if (item.objId == nodeId) {
                        this.hoverItem.alertLevel = item.alertLevel || '-';
                        this.hoverItem.flow = item.flow || '-';
                        this.hoverItem.limitTraffic = item.limitTraffic || '-';
                        this.hoverItem.waterLevel = item.waterLevel || '-';
                    }
                });
            }
        }
        if (event === 'moveOutNode') {
            this.infoShow = false;
        }
        if (event === 'node') {
            // alert(node.data.name + '被点击了');
        }
    }

    // 防抖函数
    debounce(func, wait?, immediate?): any {
        let timeout;
        return function() {
            const context = this;
            const args = arguments;
            const later = () => {
                timeout = null;
                if (!immediate) {
                    func.apply(context, args);
                }
            };
            const callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) {
                func.apply(context, args);
            }
        };
    }
}
